package com.example.config;

import com.example.Utils.CookieUtil;
import com.example.entity.User;
import com.example.service.UserService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {

        Class<?> clazz = methodParameter.getParameterType();
        return clazz == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        System.out.println("1=====addArgumentResolvers======resolveArgument===========");

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String ticket = "";
        try {
            ticket = CookieUtil.getUid(request, "userticket");
        } catch (Exception e) {
            response.sendRedirect(request.getContextPath() + "/tologin");

        }

        //System.out.println("2=============" + ticket);
        if (StringUtil.isNullOrEmpty(ticket)) {
            return null;
        }
        User user = userService.getUserByCookie(ticket, request, response);
        if (user == null) {
            System.out.println("userArgumentResolver中user为空=======");
            response.sendRedirect(request.getContextPath() + "/tologin");
        }
        return user;
    }
}
